﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.TestManagement.Client;
using TestStepsEditor.Viewers.Data;

namespace TestStepsEditor.Actions
{
    internal class Rows
    {
        public static BindingList<SimpleStep> Delete(SharedData data)
        {
            if (data.GridView.SelectedRows.Count > 0)
            {
                foreach (DataGridViewRow row in data.GridView.SelectedRows)
                {
                    if (row != null)
                    {
                        if (row.ReadOnly == false)
                        {
                            data.StepsCollection.RemoveAt(data.GridView.Rows.IndexOf(row));
                            data.GridView.Focus();
                        }
                        else
                        {
                            if (row.Index != -1)
                            {
                                foreach (
// ReSharper disable AccessToModifiedClosure
                                    var step in data.StepsCollection.GroupBy(step => row.Cells["GroupByIndexer"].Value))
// ReSharper restore AccessToModifiedClosure
                                {
                                    foreach (var simpleStep in step)
                                    {
                                        if (simpleStep.GroupByIndexer == Convert.ToInt32(step.Key))
                                            data.StepsCollection.Remove(simpleStep);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (data.GridView.CurrentRow != null)
                {
                    if (data.GridView.CurrentRow.ReadOnly == false)
                    {
                        data.StepsCollection.RemoveAt(data.GridView.CurrentRow.Index);
                        data.GridView.Focus();
                    }
                }
            }
            return data.StepsCollection;
        }

        public static MainForm Export(SharedData data)
        {
            var form = new InsertRowsForm();
            form.ShowDialog();
            if (form.TFSID == 0)
            {
                if (form.WIType == "T")
                    form.TFSID = WorkItems.New("T", data);

                if (form.WIType == "S")
                    form.TFSID = WorkItems.New("S", data);
            }

            if (form.TFSID != 0)
            {
                var mainForm = new MainForm(Convert.ToInt32(form.TFSID));
                int rowIndex;
                if (form.RowNumber != "")
                    rowIndex = Convert.ToInt32(form.RowNumber);
                else
                {
                    rowIndex = mainForm.Data.GridView.Rows.GetLastRow(DataGridViewElementStates.None);
                    rowIndex++;
                }
                foreach (DataGridViewRow row in
                    data.GridView.SelectedRows.Cast<DataGridViewRow>().Where(row => row.ReadOnly != true))
                {
                    mainForm.Data.StepsCollection.Insert(rowIndex,
                                                         new SimpleStep(null,
                                                                        row.Cells["Title"].Value.ToString().Replace(
                                                                            "\r", ""),
                                                                        row.Cells["ExpectedResult"].Value.ToString().
                                                                            Replace("\r", ""),
                                                                        false, 0, mainForm.Data.GroupIndexer,
                                                                        row.Cells["Attachment"].Value as
                                                                        IAttachmentCollection));
                    mainForm.Data.GroupIndexer++;
                }
                mainForm.Show();
                mainForm.Data.GridView = mainForm.workItemGridView;
                mainForm.Data = InsertImages.AddImageToGrid(mainForm.Data);
                mainForm.workItemGridView = mainForm.Data.GridView;
                mainForm.workItemGridView.Refresh();
                mainForm.workItemGridView.AutoResizeRows();
                mainForm.workItemGridView = MakeSharedStepsReadOnly(mainForm.workItemGridView);
                mainForm.workItemGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
                mainForm.Refresh();
                return mainForm;
            }
            else
            {
                MessageBox.Show(@"Rows not copied please try again.");
            }
            return null;
        }

        public static DataGridView MakeSharedStepsReadOnly(DataGridView workItemGridView)
        {
            foreach (DataGridViewRow item in workItemGridView.Rows)
            {
                if (item.Cells[1].Value != null && item.Cells[2].Value.Equals(true))
                {
                    item.ReadOnly = true;
                    item.DefaultCellStyle.ForeColor = Color.Gray;
                }
            }
            return workItemGridView;
        }

        public static SharedData InsertSharedStep(int sharedStepId, SharedData data)
        {
            ISharedStep sharedStep = data.TestProject.SharedSteps.Find(sharedStepId);
            if (data.GridView.CurrentRow != null)
            {
                int rowIndexer = data.GridView.CurrentRow.Index;
                rowIndexer++;
                foreach (ITestAction action in sharedStep.Actions)
                {
                    var step = action as ITestStep;
                    if (step != null)
                    {
                        data.StepsCollection.Insert(rowIndexer,
                                                    new SimpleStep(null, step.Title.ToString(),
                                                                   step.ExpectedResult.ToString(),
                                                                   true,
                                                                   sharedStep.Id, data.GroupIndexer, null));
                        data.GridView.Rows[rowIndexer].ReadOnly = true;
                        foreach (DataGridViewCell cell in data.GridView.Rows[rowIndexer].Cells)
                        {
                            cell.Style.ForeColor = Color.Gray;
                        }
                    }
                    rowIndexer++;
                }
            }
            data.GroupIndexer++;
            if (data.GridView.Columns.Contains("image"))
                data.GridView.Columns.Remove("image");
            data = InsertImages.AddImageToGrid(data);
            return data;
        }

        public static SharedData InsertSimpleStep(SharedData data)
        {
            if (data.GridView.CurrentRow != null)
            {
                if (data.GridView.CurrentRow.ReadOnly != true)
                {
                    if (data.GridView.CurrentRow.Index ==
                        data.GridView.Rows.GetLastRow(DataGridViewElementStates.None))
                    {
                        data.StepsCollection.Insert(data.GridView.CurrentRow.Index + 1,
                                                    new SimpleStep(null, "", "", false, 0, data.GroupIndexer, null));
                        DataGridViewRow desiredCell = data.GridView.Rows[data.GridView.CurrentRow.Index + 1];
                        data.GridView.CurrentCell = desiredCell.Cells["Title"];
                    }
                    else
                    {
                        data.StepsCollection.Insert(data.GridView.CurrentRow.Index,
                                                    new SimpleStep(null, "", "", false, 0, data.GroupIndexer, null));
                        DataGridViewRow desiredCell = data.GridView.Rows[data.GridView.CurrentRow.Index - 1];
                        data.GridView.CurrentCell = desiredCell.Cells["Title"];
                    }
                    data.GridView.CurrentRow.DefaultCellStyle.ForeColor = Color.Blue;
                    data.GridView.CurrentCell.Value = "<Insert new test Step>";
                    data.GridView.Focus();
                    data.GroupIndexer++;
                }

                if (data.GridView.CurrentRow != null)
                {
                    if (data.GridView.CurrentRow.ReadOnly &&
                        data.GridView.CurrentRow.Index ==
                        data.GridView.Rows.GetLastRow(DataGridViewElementStates.Displayed))
                    {
                        data.StepsCollection.Insert(data.GridView.CurrentRow.Index + 1,
                                                    new SimpleStep(null, "", "", false, 0, data.GroupIndexer, null));
                        DataGridViewRow desiredCell = data.GridView.Rows[data.GridView.CurrentRow.Index + 1];
                        data.GridView.CurrentCell = desiredCell.Cells["Title"];
                        data.GridView.CurrentRow.DefaultCellStyle.ForeColor = Color.Blue;
                        data.GridView.CurrentCell.Value = "<Insert new test Step>";
                        data.GridView.Focus();
                        data.GroupIndexer++;
                    }
                    if (data.GridView.CurrentRow != null)
                        if (data.GridView.CurrentRow.ReadOnly &&
                            (data.GridView.Rows[data.GridView.CurrentRow.Index + 1].ReadOnly == false))
                        {
                            data.StepsCollection.Insert(data.GridView.CurrentRow.Index + 1,
                                                        new SimpleStep(null, "", "", false, 0, data.GroupIndexer, null));
                            DataGridViewRow desiredCell = data.GridView.Rows[data.GridView.CurrentRow.Index + 1];
                            data.GridView.CurrentCell = desiredCell.Cells["Title"];
                            data.GridView.CurrentRow.DefaultCellStyle.ForeColor = Color.Blue;
                            data.GridView.CurrentCell.Value = "<Insert new test Step>";
                            data.GridView.Focus();
                            data.GroupIndexer++;
                        }
                }
                var dataGridViewCellStyle =
                    new DataGridViewCellStyle {NullValue = null, Tag = "BLANK"};
                if (data.GridView.Columns.Contains("image"))
                    if (data.GridView.CurrentRow != null)
                        data.GridView.CurrentRow.Cells["image"].Style = dataGridViewCellStyle;
            }
            else
            {
                data.StepsCollection.Insert(0, new SimpleStep(null, "", "", false, 0, data.GroupIndexer, null));
                DataGridViewRow desiredCell = data.GridView.Rows[0];
                data.GridView.CurrentCell = desiredCell.Cells["Title"];
                if (data.GridView.CurrentRow != null) data.GridView.CurrentRow.DefaultCellStyle.ForeColor = Color.Blue;
                data.GridView.CurrentCell.Value = "<Insert new test Step>";
                data.GridView.Focus();
                data.GroupIndexer++;
                var dataGridViewCellStyle =
                    new DataGridViewCellStyle();
                dataGridViewCellStyle.NullValue = null;
                dataGridViewCellStyle.Tag = "BLANK";
                if (data.GridView.Columns.Contains("image"))
                    if (data.GridView.CurrentRow != null)
                        data.GridView.CurrentRow.Cells["image"].Style = dataGridViewCellStyle;
            }
            return data;
        }

        public static SharedData Copy(SharedData data)
        {
            data.CopiedRows = new DataGridViewRow[data.GridView.SelectedRows.Count];
            data.GridView.SelectedRows.CopyTo(data.CopiedRows, 0);
            return data;
        }

        public static SharedData InsertCopiedRow(SharedData data)
        {
            if (data.CopiedRows != null)
            {
                IEnumerable<DataGridViewRow> query = data.CopiedRows.OrderBy(row => row.Index);
                foreach (DataGridViewRow row in query)
                {
                    if (data.GridView.CurrentRow != null)
                    {
                        if (data.GridView.CurrentRow.ReadOnly != true)
                        {
                            if (data.GridView.CurrentRow.Index ==
                                data.GridView.Rows.GetLastRow(DataGridViewElementStates.None))
                            {
                                data.StepsCollection.Insert(data.GridView.CurrentRow.Index + 1,
                                                            new SimpleStep(null, row.Cells["Title"].Value.ToString(),
                                                                           row.Cells["ExpectedResult"].Value.ToString(),
                                                                           false, 0,
                                                                           data.GroupIndexer, null, false));
                                DataGridViewRow desiredCell = data.GridView.Rows[data.GridView.CurrentRow.Index + 1];
                                data.GridView.CurrentCell = desiredCell.Cells[0];
                                data.GridView.CurrentRow.DefaultCellStyle.ForeColor = Color.Blue;
                            }
                            else
                            {
                                data.StepsCollection.Insert(data.GridView.CurrentRow.Index,
                                                            new SimpleStep(null, row.Cells["Title"].Value.ToString(),
                                                                           row.Cells["ExpectedResult"].Value.ToString(),
                                                                           false, 0,
                                                                           data.GroupIndexer, null, false));
                                data.GridView.Rows[data.GridView.CurrentRow.Index - 1].DefaultCellStyle.ForeColor =
                                    Color.Blue;
                            }
                            data.GridView.Focus();
                            data.GroupIndexer++;
                        }

                        if (data.GridView.CurrentRow != null)
                        {
                            if (data.GridView.CurrentRow.ReadOnly &&
                                data.GridView.CurrentRow.Index ==
                                data.GridView.Rows.GetLastRow(DataGridViewElementStates.Displayed))
                            {
                                data.StepsCollection.Insert(data.GridView.CurrentRow.Index + 1,
                                                            new SimpleStep(null, row.Cells["Title"].Value.ToString(),
                                                                           row.Cells["ExpectedResult"].Value.ToString(),
                                                                           false, 0,
                                                                           data.GroupIndexer, null, false));
                                data.GridView.Rows[data.GridView.CurrentRow.Index + 1].DefaultCellStyle.ForeColor =
                                    Color.Blue;
                                data.GridView.Focus();
                                data.GroupIndexer++;
                            }
                            if (data.GridView.CurrentRow != null)
                                if (data.GridView.CurrentRow.ReadOnly &&
                                    (data.GridView.Rows[data.GridView.CurrentRow.Index + 1].ReadOnly == false))
                                {
                                    data.StepsCollection.Insert(data.GridView.CurrentRow.Index + 1,
                                                                new SimpleStep(null, row.Cells["Title"].Value.ToString(),
                                                                               row.Cells["ExpectedResult"].Value.
                                                                                   ToString(), false, 0,
                                                                               data.GroupIndexer, null, false));
                                    data.GridView.Rows[data.GridView.CurrentRow.Index + 1].DefaultCellStyle.ForeColor =
                                        Color.Blue;
                                    data.GridView.Focus();
                                    data.GroupIndexer++;
                                }
                        }
                        InsertImages.AddImageToGrid(data);
                    }
                }
            }
            return data;
        }

        public static List<DataGridViewCell> Find(SharedData data, string text)
        {
            var rowsWithText = new List<DataGridViewCell>();
            foreach (DataGridViewRow row in data.GridView.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.Value != null)
                    {
                        if (cell.Value.ToString().IndexOf(text, StringComparison.OrdinalIgnoreCase) != -1)
                            rowsWithText.Add(cell);
                    }
                }
            }
            return rowsWithText;
        }
    }
}